const { app, Menu, BrowserWindow } = require("electron");
const fs = require("fs");
// const v8 = require("v8");
const path = require("path");
const axios = require("axios");

const REMOTE_BASE_URL =
  "https://bim-1302331233.cos.ap-chengdu.myqcloud.com/ezBridge/dist";
let exe_dir;
const appOptions = {};

function getFullUrl(url) {
  return `${REMOTE_BASE_URL}/${url}`;
}

function getRemoteFile(url) {
  url = getFullUrl(url);
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then((response) => {
        const data = response.data;
        resolve(data);
      })
      .catch((err) => {
        console.error(err);
        reject(err);
      });
  });
}

function createWindow(url) {
  const options = {
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      spellcheck: false,
      zoomFactor: 1,
      // partition: appOptions.partition,
    },
    icon: path.join(__dirname, "icon.png"),
  };
  // console.log(options);
  const win = new BrowserWindow(options);
  win.webContents.openDevTools();
  // win.maximize();
  // win.webContents.reload();
  win.webContents.setVisualZoomLevelLimits(0.75, 3);

  win.loadURL(getFullUrl(url)).then(() => {
    win.setTitle(appOptions.title || "梁桥轻量化快速建模工具");
  });
}

const optionsPromise = getRemoteFile("config/menu.json");

app.on("ready", () => {
  const currentDir = process.execPath;
  exe_dir = path.dirname(currentDir);

  optionsPromise
    .then((options) => {
      Object.assign(appOptions, options);
      options.menu.forEach((item) => {
        item.submenu.forEach((subItem) => {
          if (subItem.url) {
            subItem.click = () => {
              createWindow(subItem.url);
            };
          }
        });
      });

      const menu = Menu.buildFromTemplate(options.menu);
      Menu.setApplicationMenu(menu);

      createWindow("index.html");
    })
    .catch((err) => {
      console.error(err);
    });
});

app.on("window-all-closed", () => {
  if (process.platform === "darwin") return;
  app.quit();
});

exports.app = app;
